<template>
  <div class='voice-player-wrapper'
      :class='{ rtl: direction === "rtl" }'
       @click.stop='togglePlay'>
    <div class='voice-player-body'
        :style='{ backgroundColor: bgColor }'>
      <span class='voice-arrow'
           :style='{ borderRightColor: bgColor }'>
      </span>
      <span class='voice-icon'
           :class='{ playing: status === "play" }'>
      </span>
      <div class='voice-progress'>
        <div class='voice-progress-line'
            :style='{
              width: progress,
              backgroundColor: progressColor
            }'>
        </div>
      </div>
    </div>
    <audio :src='voiceUrl'
           controls="controls"
           preload
           hidden
           :ref='audioId'>
    </audio>
  </div>
</template>

<script>
import BenzAMRRecorder from 'benz-amr-recorder'
export default {
  name: 'voicePlayer',
  data () {
    return {
      status: 'paused',
      voice: {},
      isAmr: false,
      audioId: '',
      duration: 0,
      progress: '0%',
      timer: null,
      invalidVoice: false
    }
  },
  props: {
    // 语音文件的地址
    voiceUrl: {
      type: String,
      default: ''
    },
    // 控制展示的方向，可选值：ltr, rtl
    direction: {
      type: String,
      default: 'ltr' // 从左到右展示
    },
    // 背景颜色
    bgColor: {
      type: String,
      default: '#96EC69'
    },
    // 进度条颜色
    progressColor: {
      type: String,
      default: '#6fdb36'
    }
  },
  methods: {
    togglePlay () {
      if (this.invalidVoice) {
        return this.$message({
          type: 'warning',
          message: '不支持的音频格式'
        })
      }
      if (this.status === 'paused') {
        this.status = 'play'
        if (this.isAmr) {
          this.voice.playOrResume()
        } else {
          this.voice.play()
        }
        window.eventBus.$emit('startPlay', this.audioId)
        this.timer = setInterval(() => {
          this.updateProgress()
        }, 300)
      } else {
        this.status = 'paused'
        this.voice.pause()
        clearInterval(this.timer)
      }
    },
    updateProgress () {
      let currPos
      if (this.isAmr) {
        currPos = this.voice.getCurrentPosition()
      } else {
        currPos = this.voice.currentTime
      }
      this.progress = (currPos / this.duration) * 100 + '%'
    },
    init () {
      // 如果是silk后缀名的音频文件，则不支持播放
      if (/\.silk$/.test(this.voiceUrl)) {
        this.invalidVoice = true
      }
      // 如果是amr格式的文件
      if (/\.amr$/.test(this.voiceUrl)) {
        this.isAmr = true
        this.voice = new BenzAMRRecorder()
        this.voice.initWithUrl(this.voiceUrl).then(() => {
          this.duration = this.voice.getDuration()
          // console.log('amr 准备就绪', this.duration)
          this.voice.onEnded(() => {
            // console.log('amr播放结束')
            this.status = 'paused'
            clearInterval(this.timer)
            this.progress = '100%'
          })
        })
      // 如果不是amr格式文件，使用audio播放
      } else {
        this.isAmr = false
        this.$nextTick(() => {
          this.voice = this.$refs[this.audioId]
          this.voice.oncanplay = () => {
            this.duration = this.voice.duration
          }
          this.voice.onended = () => {
            this.status = 'paused'
            clearInterval(this.timer)
            this.progress = '100%'
          }
        })
      }
    }
  },
  created () {
    this.audioId = this.createUniqueId()
    this.init()
    // 点击某一个播放组件，其他播放组件自动暂定
    window.eventBus.$on('startPlay', audioId => {
      if (audioId !== this.audioId) {
        this.status = 'paused'
        this.voice.pause()
        clearInterval(this.timer)
      }
    })
  },
  beforeDestroy () {
    this.voice.pause()
    this.status = 'paused'
    this.progress = '0%'
    clearInterval(this.timer)
    window.eventBus.$off('startPlay')
  }
}
</script>

<style lang='stylus' scoped>
.voice-player-wrapper
  cursor pointer
  &.rtl
    transform rotate(180deg)
  .voice-player-body
    position relative
    width 112px
    height 35px
    border-radius 4px
    .voice-arrow
      display block
      width 0
      height 0
      border-color transparent #96EC69 transparent transparent
      border-style solid
      border-width 6px 8px 6px 0px
      position absolute
      left -8px
      top 50%
      transform translate(0, -50%)
    .voice-icon
      position absolute
      left 10px
      top 0
      bottom 0
      z-index 10
      margin auto
      width 24px
      height 24px
      background url('~assets/img/enterprise/icon_left_audio_play3@2x.png') no-repeat 0 0 / 24px
      &.playing
        animation: fadeInOut 1.5s infinite;
      @keyframes fadeInOut{
        0% {
          background-image:url('~assets/img/enterprise/icon_left_audio_play1@2x.png');
        }
        25% {
          background-image:url('~assets/img/enterprise/icon_left_audio_play2@2x.png');
        }
        50% {
          background-image:url('~assets/img/enterprise/icon_left_audio_play3@2x.png');
        }
        75% {
          background-image:url('~assets/img/enterprise/icon_left_audio_play2@2x.png');
        }
        100% {
          background-image:url('~assets/img/enterprise/icon_left_audio_play1@2x.png');
        }
      }
    .voice-progress
      position absolute
      left 0
      top 0
      bottom 0
      width 100%
      height 100%
      border-radius 4px
      overflow hidden
      .voice-progress-line
        height 100%
</style>
